let pollData = null;
let chart = null;
let pollId = window.location.pathname.split('/').pop();

// 获取投票详情
async function loadPoll() {
    try {
        const response = await fetch(`/api/poll/${pollId}`);
        if (!response.ok) {
            if (response.status === 404) {
                document.body.innerHTML = '<div class="container mt-5"><div class="alert alert-danger">投票不存在</div></div>';
                return;
            }
            throw new Error('加载失败');
        }
        
        pollData = await response.json();
        displayPoll();
        displayResults();
        loadQRCode();
    } catch (error) {
        console.error('Error loading poll:', error);
        document.body.innerHTML = '<div class="container mt-5"><div class="alert alert-danger">加载投票失败</div></div>';
    }
}

// 显示投票内容
function displayPoll() {
    document.getElementById('pollTitle').textContent = pollData.title;
    
    const container = document.getElementById('optionsContainer');
    container.innerHTML = '';
    
    const inputType = pollData.multiple_choice ? 'checkbox' : 'radio';
    const inputName = pollData.multiple_choice ? 'voteOptions' : 'voteOption';
    
    pollData.options.forEach((option, index) => {
        const div = document.createElement('div');
        div.className = 'vote-option';
        div.innerHTML = `
            <div class="form-check">
                <input class="form-check-input" type="${inputType}" 
                       name="${inputName}" value="${index}" id="option${index}">
                <label class="form-check-label" for="option${index}">
                    ${option}
                </label>
            </div>
        `;
        container.appendChild(div);
    });
}

// 显示投票结果
function displayResults() {
    document.getElementById('totalVotes').textContent = pollData.total_votes;
    
    // 更新图表
    updateChart();
    
    // 更新结果表格
    const tableContainer = document.getElementById('resultsTable');
    tableContainer.innerHTML = '';
    
    pollData.options.forEach((option, index) => {
        const percentage = pollData.percentages[index].toFixed(1);
        const count = pollData.vote_counts[index];
        
        const div = document.createElement('div');
        div.className = 'result-item';
        div.innerHTML = `
            <div>
                <strong>${option}</strong>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" 
                         style="width: ${percentage}%" 
                         aria-valuenow="${percentage}" 
                         aria-valuemin="0" 
                         aria-valuemax="100">
                        ${percentage}%
                    </div>
                </div>
                <small class="text-muted">${count} 票</small>
            </div>
        `;
        tableContainer.appendChild(div);
    });
}

// 更新图表
function updateChart() {
    const ctx = document.getElementById('resultsChart').getContext('2d');
    
    if (chart) {
        chart.destroy();
    }
    
    chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: pollData.options,
            datasets: [{
                label: '票数',
                data: pollData.vote_counts,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.8)',
                    'rgba(54, 162, 235, 0.8)',
                    'rgba(255, 205, 86, 0.8)',
                    'rgba(75, 192, 192, 0.8)',
                    'rgba(153, 102, 255, 0.8)',
                    'rgba(255, 159, 64, 0.8)',
                    'rgba(199, 199, 199, 0.8)',
                    'rgba(83, 102, 255, 0.8)',
                    'rgba(40, 159, 64, 0.8)',
                    'rgba(210, 199, 199, 0.8)'
                ],
                borderColor: [
                    'rgb(255, 99, 132)',
                    'rgb(54, 162, 235)',
                    'rgb(255, 205, 86)',
                    'rgb(75, 192, 192)',
                    'rgb(153, 102, 255)',
                    'rgb(255, 159, 64)',
                    'rgb(199, 199, 199)',
                    'rgb(83, 102, 255)',
                    'rgb(40, 159, 64)',
                    'rgb(210, 199, 199)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}

// 加载二维码
async function loadQRCode() {
    try {
        const response = await fetch(`/api/qrcode/${pollId}`);
        const data = await response.json();
        document.getElementById('shareQR').src = data.qr_code;
        document.getElementById('shareLink').value = window.location.href;
    } catch (error) {
        console.error('Error loading QR code:', error);
    }
}

// 复制分享链接
function copyShareLink() {
    const linkInput = document.getElementById('shareLink');
    linkInput.select();
    document.execCommand('copy');
    
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-check"></i>';
    setTimeout(() => {
        button.innerHTML = originalText;
    }, 2000);
}

// 刷新结果
async function refreshResults() {
    try {
        const response = await fetch(`/api/poll/${pollId}`);
        pollData = await response.json();
        displayResults();
    } catch (error) {
        console.error('Error refreshing results:', error);
        alert('刷新结果失败，请重试！');
    }
}

// 显示管理员视图
async function showAdminView() {
    try {
        const response = await fetch(`/api/admin/${pollId}`);
        if (!response.ok) {
            throw new Error('获取管理员数据失败');
        }
        
        const adminData = await response.json();
        displayAdminView(adminData);
        
        const modal = new bootstrap.Modal(document.getElementById('adminModal'));
        modal.show();
    } catch (error) {
        console.error('Error loading admin data:', error);
        alert('获取管理员数据失败！');
    }
}

// 显示管理员视图内容
function displayAdminView(data) {
    const content = document.getElementById('adminContent');
    
    let html = `
        <h6>投票标题：${data.title}</h6>
        <p>总投票数：${data.total_votes}</p>
        <div class="table-responsive">
            <table class="table table-striped table-sm admin-table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>选项</th>
                        <th>投票者ID</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    data.detailed_votes.forEach(vote => {
        const time = new Date(vote.voted_at).toLocaleString('zh-CN');
        html += `
            <tr>
                <td>${time}</td>
                <td>${vote.option}</td>
                <td>${vote.voter_id}</td>
            </tr>
        `;
    });
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    content.innerHTML = html;
}

// 投票表单提交
document.getElementById('voteForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const selectedOptions = [];
    const checkboxes = document.querySelectorAll('input[name="voteOptions"]:checked, input[name="voteOption"]:checked');
    
    checkboxes.forEach(checkbox => {
        selectedOptions.push(parseInt(checkbox.value));
    });
    
    if (selectedOptions.length === 0) {
        alert('请至少选择一个选项！');
        return;
    }
    
    try {
        const response = await fetch(`/api/vote/${pollId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                options: selectedOptions
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            alert('投票成功！');
            // 刷新结果
            await refreshResults();
            // 清空选择
            document.querySelectorAll('input[type="checkbox"], input[type="radio"]').forEach(input => {
                input.checked = false;
            });
        } else {
            alert(data.error || '投票失败，请重试！');
        }
    } catch (error) {
        console.error('Error voting:', error);
        alert('投票失败，请检查网络连接！');
    }
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', loadPoll);
